import { db } from "../database/connection"
import { userSubscriptions } from "../database/schema"
import { eq } from "drizzle-orm"

export class LemonSqueezyService {
  private static get apiKey() {
    const config = useRuntimeConfig()
    return config.lemonSqueezyApiKey || ""
  }

  private static baseUrl = "https://api.lemonsqueezy.com/v1"

  static async createCheckoutSession(userId: number, variantId: string) {
    if (!this.apiKey) {
      console.warn("LemonSqueezy API key not configured")
      return "https://example.com/checkout"
    }

    try {
      const config = useRuntimeConfig()
      const response = await $fetch(`${this.baseUrl}/checkouts`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
          Accept: "application/vnd.api+json",
          "Content-Type": "application/vnd.api+json",
        },
        body: {
          data: {
            type: "checkouts",
            attributes: {
              checkout_data: {
                custom: {
                  user_id: userId.toString(),
                },
              },
            },
            relationships: {
              store: {
                data: {
                  type: "stores",
                  id: config.lemonSqueezyStoreId || "",
                },
              },
              variant: {
                data: {
                  type: "variants",
                  id: variantId,
                },
              },
            },
          },
        },
      })

      return response.data.attributes.url
    } catch (error) {
      console.error("Error creating checkout session:", error)
      return "https://example.com/checkout"
    }
  }

  static async handleWebhook(payload: any, signature: string) {
    const config = useRuntimeConfig()
    const webhookSecret = config.lemonSqueezyWebhookSecret

    if (!webhookSecret) {
      console.warn("LemonSqueezy webhook secret not configured")
      return
    }

    try {
      // 验证webhook签名
      const crypto = await import("crypto")
      const hmac = crypto.createHmac("sha256", webhookSecret)
      hmac.update(JSON.stringify(payload))
      const expectedSignature = hmac.digest("hex")

      if (signature !== expectedSignature) {
        throw new Error("Invalid webhook signature")
      }

      const { meta, data } = payload

      switch (meta.event_name) {
        case "subscription_created":
        case "subscription_updated":
          await this.handleSubscriptionUpdate(data)
          break
        case "subscription_cancelled":
          await this.handleSubscriptionCancellation(data)
          break
        case "subscription_expired":
          await this.handleSubscriptionExpiration(data)
          break
      }
    } catch (error) {
      console.error("Error handling webhook:", error)
      throw error
    }
  }

  private static async handleSubscriptionUpdate(data: any) {
    try {
      const userId = Number.parseInt(data.attributes.custom_data?.user_id)
      if (!userId) return

      const subscription = {
        userId,
        provider: "lemonsqueezy",
        subscriptionId: data.id,
        planId: data.attributes.variant_id,
        status: data.attributes.status,
        currentPeriodStart: new Date(data.attributes.current_period_start),
        currentPeriodEnd: new Date(data.attributes.current_period_end),
        trialEndDate: data.attributes.trial_ends_at ? new Date(data.attributes.trial_ends_at) : null,
        updatedAt: new Date(),
      }

      // 检查是否已存在订阅
      const existing = await db
        .select()
        .from(userSubscriptions)
        .where(eq(userSubscriptions.subscriptionId, data.id))
        .limit(1)

      if (existing.length > 0) {
        await db.update(userSubscriptions).set(subscription).where(eq(userSubscriptions.subscriptionId, data.id))
      } else {
        await db.insert(userSubscriptions).values(subscription)
      }
    } catch (error) {
      console.error("Error handling subscription update:", error)
    }
  }

  private static async handleSubscriptionCancellation(data: any) {
    try {
      await db
        .update(userSubscriptions)
        .set({
          status: "cancelled",
          updatedAt: new Date(),
        })
        .where(eq(userSubscriptions.subscriptionId, data.id))
    } catch (error) {
      console.error("Error handling subscription cancellation:", error)
    }
  }

  private static async handleSubscriptionExpiration(data: any) {
    try {
      await db
        .update(userSubscriptions)
        .set({
          status: "expired",
          updatedAt: new Date(),
        })
        .where(eq(userSubscriptions.subscriptionId, data.id))
    } catch (error) {
      console.error("Error handling subscription expiration:", error)
    }
  }

  static async getSubscriptionPlans() {
    if (!this.apiKey) {
      console.warn("LemonSqueezy API key not configured, returning mock plans")
      return [
        {
          id: "1",
          name: "Pro Monthly",
          price: 999,
          interval: "month",
          description: "Monthly Pro subscription",
        },
        {
          id: "2",
          name: "Pro Yearly",
          price: 9999,
          interval: "year",
          description: "Yearly Pro subscription",
        },
      ]
    }

    try {
      const response = await $fetch(`${this.baseUrl}/variants`, {
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
          Accept: "application/vnd.api+json",
        },
      })

      return response.data.map((variant: any) => ({
        id: variant.id,
        name: variant.attributes.name,
        price: variant.attributes.price,
        interval: variant.attributes.interval,
        description: variant.attributes.description,
      }))
    } catch (error) {
      console.error("Error fetching subscription plans:", error)
      return []
    }
  }
}
